import math
from datetime import datetime

from flask import Flask, Blueprint, jsonify, request

from db import db

test_bp = Blueprint("test_bp", __name__)


# TODO



@test_bp.route('/login')
def login():
    name = request.args.get('name')
    if not name:
        return jsonify({"code": 400, "msg": "不能为空"})
    # sql = "select * from user where name='%s'" % name
    sql = "select user.id as uid,role.id as rid,role.url as url from user inner join role on user.id=role.user_id where user.name='%s'" % name
    res = db.find(sql)
    if not res:
        return jsonify({"code": 400, "msg": "不存在"})

    return jsonify({"code": 200, "msg": "成功", "data": res})


@test_bp.route('/data')
def data():
    uid = request.args.get('uid')
    rid = request.args.get('rid')
    if not rid:
        return jsonify({"code": 400, "msg": "没数据"})
    sql = f"select role.name as rname,role.id as rid,resource.name as resname,resource.id as reid from role inner join role_resource on {rid}=role_resource.role_id " \
          f" inner join resource on role_resource.resource_id = resource.id where role.user_id = {uid}"

    # sql = f"select * from role inner join role_resource on {rid}=role_resource.role_id " \
    #       f" inner join resource on role_resource.resource_id = resource.id where role.user_id = {uid}"

    # sql="select * from role inner join role_resource on {rid}=role_resource.role_id"

    res = db.find_all(sql)
    return jsonify({"code": 200, "res": res})


@test_bp.route('/send')
def send():
    data = request.args.get('data')
    uid = request.args.get('uid')
    days = int(request.args.get('days'))
    etime = request.args.get('etime')
    if not uid or not data or not days or not etime:
        return jsonify({"code": 400, "msg": "数据必填"})
    sql = f"insert into qj(uid, type,days,etime) values({uid},'{data}',{days},DATE_FORMAT('{etime}','%Y-%m-%d %H:%m:%S'))"
    # sql = f"insert into qj(uid, name,days,etime) values({uid},'{data}',{days},'2022-10-14 00:00:00')"
    print(sql)
    db.update(sql)
    db.commit()

    return jsonify({"code": 200, "msg": "上传成功"})


@test_bp.route('/showdata')
def showdata():
    uid = request.args.get('uid')
    if not uid:
        return jsonify({"code": 400, "msg": "数据必填"})
    # sql = f"SELECT qj.id as qid,qj.name as qname,role.name as rname,user.name as uname FROM qj LEFT JOIN role ON qj.next=role.id RIGHT JOIN USER ON role.user_id=user.id WHERE qj.uid={uid}"
    sql = f"select qj.id as qid,qj.type as qname,user.name as uname from qj left join user on qj.next=user.id where next=2"
    # sql = "SELECT * FROM qj LEFT JOIN role ON qj.next=role.id RIGHT JOIN USER ON role.user_id=user.id WHERE qj.uid=1;"
    # print(sql)
    res = db.find_all(sql)
    # print(res)

    return jsonify({"code": 200, "msg": "成功", "data": res})


@test_bp.route('/shenpi')
def shenpi():
    qid = request.args.get('qid')
    status = request.args.get('status')
    print(status, type(status), "===========================")
    if not qid:
        return jsonify({"code": 400, "msg": "选哪条"})
    if int(status) == 1:
        print("往这跑？？？？？？？？？？？？？？？？？？？？？？？？？？？")
        sql = f"update qj set next=NULL where id={qid}"
        db.update(sql)
        db.commit()
    else:
        print("往这跑！！！！！！！！！！！！！！！！！！！！！！！！！！！！！1")
        sql = f"select uid from qj where id={qid}"
        print(sql)
        res = db.find(sql)
        sql = f"update qj set next={res['uid']} where id={qid}"
        print(sql)
        db.update(sql)
        db.commit()
    return jsonify({"code": 200, "msg": "修改成功"})


@test_bp.route('/echarts')
def echarts():
    uid = int(request.args.get('uid'))
    # sql = "select * from money DATE_FORMATE(money.time,'%Y-%m') as date,sum(score) as score from news_score where userid=1  group by date;"
    now_time = datetime.now()
    month = now_time.strftime("%m")
    salary_list = []
    month_list = []

    # 查询每月总工资计算每日
    salary = 0
    sql = f"select salary from user where id={uid}"
    rr = db.find(sql)
    salary = rr["salary"]
    day_salary = rr["salary"] / 21
    for i in range(3):
        nmonth = int(month) - i
        if nmonth <= 0:
            nmonth = 12 - math.abs(nmonth)
        stime = datetime.strftime(datetime.now(), "%Y-" + str(nmonth) + '-01')
        list = [4, 6, 9, 11]
        if int(nmonth) in list:
            etime = datetime.strftime(datetime.now(), "%Y-" + str(nmonth) + '-30')

        else:
            etime = datetime.strftime(datetime.now(), "%Y-" + str(nmonth) + '-31')
        month_list.append(nmonth)
        sql = f"SELECT type,sum(days) as days from qj WHERE uid={uid} and time>='{stime}' and etime<='{etime}' group by type"

        res = db.find_all(sql)

        money = salary
        if len(res) >= 2:

            for i in res:

                if i["type"] == '2':

                    money = int(salary) - int(day_salary) * int(i["days"])

                    salary_list.append(money)
                else:
                    continue
        else:
            for i in res:
                if i["type"] == '2':

                    money = int(salary) - int(day_salary) * int(i["days"])
                    salary_list.append(money)
                else:
                    salary_list.append(int(money))

    return jsonify({"code": 200, "salary_list": salary_list, "month_list": month_list})
